<?php

namespace common\models;

use Yii;
use yii\db\Query;

/**
 * This is the model class for table "package_update_log".
 *
 * @property string $id
 * @property string $package_id
 * @property string $module
 * @property string $created_at
 * @property integer $user_id
 * @property string $log
 */
class PackageUpdateLog extends \yii\db\ActiveRecord
{
    const MODULE_BASE = 1;//基本信息
    const MODULE_TRANSFER = 2;//转让信息
    const MODULE_CONVERSION = 3;//流转、前期处置维护情况
    const MODULE_INVENTORY = 4;//项目清单
    const MODULE_SUBJECT = 5;//立项信息
    const MODULE_INCOME_DISTRIBUTION = 6;//团队收益分配
    const MODULE_QUOTE = 7;//报价信息
    const MODULE_OTHER = 8;//其他
    const MODULE_GROUP_USER = 9; //团队组成
    const MODULE_WORK_PLAN = 10; //工作计划
    const MODULE_PERMISSION = 12; //访问权限
    const FA_PLAN = 11; //发起协同


    private $module_array_title = array(
        self::MODULE_BASE => '基本信息',
        self::MODULE_TRANSFER => '转让信息',
        self::MODULE_CONVERSION => '流转、前期处置维护情况',
        self::MODULE_INVENTORY => '项目清单',
        self::MODULE_SUBJECT => '立项信息',
        self::MODULE_INCOME_DISTRIBUTION => '团队收益分配',
        self::MODULE_QUOTE => '报价信息',
        self::MODULE_OTHER => '其他',
        self::MODULE_GROUP_USER => '团队组成',
        self::MODULE_WORK_PLAN => '工作计划',
        self::MODULE_PERMISSION => '访问权限',
        self::FA_PLAN => '发起协同',

    );

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_update_log';
    }
    /*关联 用户*/
    public function getUserName(){
        return $this->hasOne(UserModel::className(),['id'=>'user_id']);
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'module'], 'required'],
            [['package_id', 'user_id'], 'integer'],
            [['created_at'], 'safe'],
            [['log'], 'string'],
            [['module'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包',
            'module' => '模块',
            'created_at' => '创建时间',
            'user_id' => '用户',
            'log' => '操作内容',
        ];
    }

    /**
     * module类型组成的数组
     * @return array
     */
    public function getModuleArrayTitle()
    {
        return $this->module_array_title;
    }

    public function add($packageId, $userId, $module, $log)
    {
        $ModuleArrayTitle = $this->getModuleArrayTitle();
        $this->package_id = $packageId;
        $this->module = $ModuleArrayTitle[$module];
        $this->created_at = date('Y-m-d H:i:s');
        $this->user_id = Yii::$app->user->id;
        $this->log = $log;
        return $this->save();
    }

    /**
     * 修改资产包用户
     * @param $packageId  资产包id
     * @return array  一维数组 用户id键，realname为值
     */
    public function getUsers($packageId)
    {
        $query = new Query();
        $users = $query->select(['p.user_id id', 'user.realname'])
            ->from(['p' => $this->tableName()])
            ->join('left join', 'user', 'user.id=p.user_id')
            ->where(['p.package_id'=>$packageId])
            ->groupBy('p.user_id')
            ->orderBy(['id' => SORT_ASC])
            ->all();

        return yii\helpers\ArrayHelper::map($users, 'id', 'realname');
    }

    /**
     * 获取总条数
     * @param $packageId 资产包id
     * @param $date  时间类型
     * @param $module 模型
     * @param $user 用户
     * @return int|string
     */
    public function getCount($packageId, $date, $module, $user)
    {
        $moduleArrayTitle = $this->getModuleArrayTitle();
        $oneWeekAgoDate = date("Y-m-d H:i:s", strtotime("-1 week"));    //一周前
        $oneMonthAgoDate = date("Y-m-d H:i:s", strtotime("-1 month"));    //一月前
        $currentDate = date('Y-m-d H:i:s', time());
        switch ($date) {
            //一周内
            case 1:
                $whereDate = ['and', ['between', 'created_at', $oneWeekAgoDate, $currentDate]];
                break;
            //一月内
            case 2:
                $whereDate = ['and', ['between', 'created_at', $oneWeekAgoDate, $currentDate]];
                break;
            //一月前
            case 3:
                $whereDate = ['and', ['<=', 'created_at', $oneMonthAgoDate]];
                break;
            //默认一月内
            default:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
        }

        $queryBulider = new yii\db\Query();
        $queryBulider
            ->select(['id', 'package_id', 'module', 'created_at', 'user_id', 'log'])
            ->from($this->tableName())
            ->where($whereDate);

        if ($packageId) {
            $wherePackageId = ['and', 'package_id=' . $packageId];
            $queryBulider->where($wherePackageId);
        }

        if ($user) {
            $whereUser = ['and', 'user_id=' . $user];
            $queryBulider->where($whereUser);
        }

        if ($module) {
            $whereModule = ['and', ['like', 'module', $moduleArrayTitle[$module]]];
            $queryBulider->where($whereModule);
        }

        $count = $queryBulider->orderBy(['id' => SORT_DESC])
            ->indexBy('id')
            ->count();

        return $count;
    }


    /**
     * 获取列表
     * @param $packageId 资产包id
     * @param $date 时间类型
     * @param $module 模型
     * @param $user 用户
     * @param int $limit 起始位置
     * @param int $offset 每页条数
     * @return array 二维
     */
    public function getList($packageId, $date, $module, $user, $limit = 0, $offset = 20)
    {
        $moduleArrayTitle = $this->getModuleArrayTitle();
        $oneWeekAgoDate = date("Y-m-d H:i:s", strtotime("-1 week"));    //一周前
        $oneMonthAgoDate = date("Y-m-d H:i:s", strtotime("-1 month"));    //一月前
        $currentDate = date('Y-m-d H:i:s', time());
        switch ($date) {
            //一周内
            case 1:
                $whereDate = ['and', ['between', 'created_at', $oneWeekAgoDate, $currentDate]];
                break;
            //一月内
            case 2:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
                break;
            //一月前
            case 3:
                $whereDate = ['and', ['<=', 'created_at', $oneMonthAgoDate]];
                break;
            //默认一月内
            default:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
        }

        $queryBulider = new yii\db\Query();

        //$sql = $queryBulider->select([])
        //    ->from('package_update_log')
        //    ->where($whereDate)
        //    ->andwhere(['and', ['package_id'=>$packageId]])
        //    ->andwhere(['and', ['user_id'=>$user]])
        //    ->offset($offset)->limit($limit)
        //    ->orderby(['id' => SORT_DESC])->createCommand()->getRawSql();
        //echo $sql;

        $queryBulider
            ->select(['id', 'package_id', 'module', 'created_at', 'user_id', 'log'])
            ->from($this->tableName())
            ->where($whereDate);

        if ($packageId) {
            $wherePackageId = ['and', 'package_id=' . $packageId];
            $queryBulider->andwhere($wherePackageId);
        }

        if ($user) {
            $whereUser = ['and', ['user_id'=>$user]];
            $queryBulider->andwhere($whereUser);
        }

        if ($module) {
            $whereModule = ['and', ['like', 'module', $moduleArrayTitle[$module]]];
            $queryBulider->andwhere($whereModule);
        }

        $queryBulider->orderBy(['id' => SORT_DESC]);

        if ($limit == 0) {
            $queryBulider->limit($offset);
        } else {
            $queryBulider->limit($limit)->offset($offset);
        }

        //$list = $queryBulider->indexBy('id')->all();
        $list = $queryBulider->all();

        $userModel = new UserModel();
        $users = $userModel->getUsers();
        if (!empty($list) && is_array($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['created_at'] = date('Y/m/d H:i:s', strtotime($value['created_at']));
                $list[$key]['user_id'] = $users[$value['user_id']];
                $list[$key]['log'] = $value['log'];

                $tmpStr = strip_tags($value['log']);
                $tmpLen = mb_strlen($tmpStr);
                $log = mb_substr($tmpStr, 0, 20, 'utf-8') . (($tmpLen > 20) ? '...' : '');
                $list[$key]['log2'] = $log;
            }
            return $list;
        }

        return array();
    }

    /**
     * 重置log字段
     * @return string
     */
    public function getLoging()
    {
        $tmpStr = strip_tags($this->log);
        $tmpLen = mb_strlen($tmpStr);
        return mb_substr($tmpStr, 0, 20, 'utf-8') . (($tmpLen > 20) ? '...' : '');
    }

}
